

const { DirImgList, sequelize } = require('./models/dirimglist');
const { ImgList } = require('./models/imglist');
const { DirList } = require('./models/dirlist');


const { exec, spawn } = require('child_process');
const fs = require('fs');
const fse = require('fs-extra');
let _ = require('lodash')

const proj4 = require('proj4');

const config = require('./config'); // 引入配置文件


// 通用配置项
// let tmpdir = 'C:/zxn/wp/tmp/'
let tmpdir = config.task.tmpdir
// let suoluetudir = 'C:/zxn/wp/suoluetu/'
let suoluetudir = config.task.suoluetudir

let tmpjsonpolygon = {
  "src_file_path": "",
}
let tmpjsonimg = {
  "input_file_path": "",
  "max_length": 1024,
  "out_rgb": 0,

}

let polygoncmd = config.task.polygoncmd
let imgcmd = config.task.imgcmd

// 获取影像信息
function getimgmessage(item, pathdir, name, allimglist) {

  const StartTime = new Date();

  let taskcount = 0

  let taskresult = {
    allimglist
  }

  // 获取包围盒
  let cmdstrpolygon = polygoncmd
  // let cmdstr = imgcmd
  tmpjsonpolygon.src_file_path = item
  let tmpjsonrespathpolygon = tmpdir + '' + _.random(0, 9999999999) + '.json'
  fs.writeFileSync(tmpjsonrespathpolygon, JSON.stringify(tmpjsonpolygon), 'utf8')

  cmdstrpolygon += tmpjsonrespathpolygon


  exec(cmdstrpolygon,{env:{GDAL_DATA: config.task.GDAL_DATA_DIR}} , (err, stdout, stderr) => {
    if (err) {
      console.error(err);
      return;
    }
    const data = fs.readFileSync(tmpjsonrespathpolygon, 'utf8');
    taskresult['data'] = JSON.parse(data)

    taskcount++
    if (taskcount == 2) {
      const EndTime = new Date();
      let costtime = EndTime - StartTime
      taskresult['costtime'] = costtime
      taskresult['name'] = name
      submititem(taskresult)
    }
  });

  // 获取缩略图
  let cmdstrimg = imgcmd
  tmpjsonimg.input_file_path = item
  let tmpjsonrespathimg = tmpdir + '' + _.random(0, 9999999999) + '.json'
  fs.writeFileSync(tmpjsonrespathimg, JSON.stringify(tmpjsonimg), 'utf8')
  cmdstrimg += tmpjsonrespathimg
  console.log(cmdstrimg);
  exec(cmdstrimg,{env:{GDAL_DATA: config.task.GDAL_DATA_DIR}} , (err, stdout, stderr) => {
    if (err) {
      console.error(err);
      return;
    }

    let name_Arr = name.split(".")
    name_Arr.pop()

    let imgname = name_Arr.join('.')

    let imgpath = pathdir + '\\' + imgname + '.thumb'
    let imgpathd = suoluetudir + '/' + imgname + _.random(0, 9999999) + '.png'
    
    try {
      fs.unlinkSync(pathdir + '\\' + imgname + '.thumb.aux.xml');
    } catch (err) {
      console.error('删除文件失败:', err);
    }

    fse.move(imgpath, imgpathd, (err) => {
      // taskresult['suoluetu'] = encodeURIComponent(imgpathd)
      taskresult['suoluetu'] = (imgpathd)
      taskcount++
      if (taskcount == 2) {
        const EndTime = new Date();
        let costtime = EndTime - StartTime
        taskresult['costtime'] = costtime
        taskresult['name'] = name
        submititem(taskresult)
      }

      if (err) throw err;
    });

    // fs.rename(imgpath, imgpathd, (err) => {
    //   if (err) {
    //     console.error('An error occurred:', err);
    //     return;
    //   }
    //   taskresult['suoluetu'] = imgpathd
    //   taskcount++
    //   if (taskcount == 2) {
    //     const EndTime = new Date();
    //     let costtime = EndTime - StartTime
    //     taskresult['costtime'] = costtime
    //     submititem(taskresult)
    //   }
    // })
  });
}

// 导出一个函数，计算地面分辨率
// console.log(calculateGroundResolution(0.000171661376953125,0));
function calculateGroundResolution(degreePerPixel, latitude) {
  // 地球半径（以米为单位）
  const earthRadius = 6371000; // 米

  // 地球周长（以米为单位）
  const earthCircumference = 2 * Math.PI * earthRadius;

  // 一度的平均地面长度（赤道上）
  const metersPerDegree = earthCircumference / 360;

  // 纬度的余弦值
  const cosLatitude = Math.cos((latitude * Math.PI) / 180);

  // 地面分辨率（米/像素）
  const groundResolution = degreePerPixel * metersPerDegree * cosLatitude;

  return groundResolution; // 返回米/像素
}

// 插入最终影像数据库 并更新任务表任务状态
async function submititem(params) {
  // console.log(params);

  // 任务列表影像列表
  await DirImgList.update(
    { zhuangtai: '1' },
    {
      where: {
        id: params.allimglist.id
      }
    }
  );

  // 任务表
  let weichuli = await DirImgList.findAll(
    {
      where: {
        zhuangtai: '0',
        dirpath: params.allimglist.dirpath
      }
    }
  );

  let yichuli = await DirImgList.findAll(
    {
      where: {
        zhuangtai: '1',
        dirpath: params.allimglist.dirpath
      }
    }
  );
  let jindu = yichuli.length / (weichuli.length + yichuli.length)

  console.log(params.allimglist.dirpath);
  console.log(jindu);


  await DirList.update(
    {
      jindu: (jindu * 100).toFixed(2) + '%',
      haoshi: params.costtime,
    },
    {
      where: {
        dirpath: params.allimglist.dirpath
      }
    }
  );

  _.forIn(global.wslist, ws => {
    let message = {
      data: {
        type: '任务项处理完成',
        jindu: (jindu * 100).toFixed(2) + '%',
        haoshi: params.costtime,
        dirpath: params.allimglist.dirpath,
        name: params.name
      }
    }
    ws.send(JSON.stringify(message)); // 发送回复
  })


  // 最终影像列表


  let itemone = {
    name: '',
    linerange: '',
    location: '',
    thumbnail: '',
    desc: '台湾',
    imgpath: '',
    imgtime: new Date(),
    remark: '',
    resolution: '',
  }

  itemone.desc = params.allimglist.miaoshu
  itemone.thumbnail = params.suoluetu
  itemone.imgpath = params.allimglist.lujing
  itemone.name = params.allimglist.filename


  itemone.imgtime = params.allimglist.shijian
  itemone.remark = params.allimglist.daxiao
  itemone.resolution = calculateGroundResolution(params.data.x_cellsize, 0)

  // 判断坐标系 统一转为4326


  itemone.linerange = {
    type: 'Polygon',
    coordinates: [params.data.real_poly]
  }
  itemone.location = {
    type: 'Point',
    coordinates: params.data.center_coording
  }


  let proj4326 = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]]'

  if (params.data.spatial_ref.split(",")[0].indexOf("4326") == -1) {
  // if (params.data.spatial_ref.indexOf("4326") == -1) {

    itemone.resolution = params.data.x_cellsize

    // 中心点坐标
    let itemproj = params.data.spatial_ref
    let respos = proj4(itemproj, proj4326, itemone.location.coordinates);
    itemone.location.coordinates = respos

    // 多边形坐标
    let respos_arr = itemone.linerange.coordinates[0].map(item => {
      return proj4(itemproj, proj4326, item);
    })
    itemone.linerange.coordinates = [respos_arr]
  }




  let itemlist = []
  itemlist.push(itemone)


  await ImgList.bulkCreate(itemlist);


  console.log('执行结束');


  // 下一个任务
  // 任务结束继续添加定时任务  如果有新任务结束定时任务
  beginTaskList()
}



// 获取记录
async function beginTaskList(params) {

  let allimglist = await DirImgList.findOne({
    order: [['createdAt', 'DESC']], // 按创建时间升序排列
    where: {
      zhuangtai: '0'
    },
  });

  if (allimglist == null) {

    backtask()
  } else {

    let pathdir = ''
    allimglist.lujing = allimglist.lujing.replaceAll('\\', '/')

    console.log(allimglist.lujing);
    if (allimglist.lujing.indexOf("/") != -1) {
      let path_arr = allimglist.lujing.split("/")
      path_arr.pop()
      pathdir = path_arr.join("/")
    } else {
      let path_arr = allimglist.lujing.split("\\")
      path_arr.pop()
      pathdir = path_arr.join("/")

    }

    getimgmessage(allimglist.lujing, pathdir, allimglist.filename, allimglist)

  }




  // await sequelize.close();
}

// getimgmessage("D:\\xiangmu\\shujuguanli\\test\\a.tif", 'D:\\xiangmu\\shujuguanli\\test', 'a.tif')

// beginTaskList()


async function backtask(params) {
  let allimglist = await DirImgList.findOne({
    order: [['createdAt', 'DESC']], // 按创建时间升序排列
    where: {
      zhuangtai: '0'
    },
  });

  if (allimglist == null) {
    setTimeout(() => {
      backtask()
      // console.log('任务扫描');
      _.forIn(global.wslist, ws => {
        let message = {
          data: {
            type: '任务扫描'
          }
        }
        ws.send(JSON.stringify(message)); // 发送回复
      })
    }, 1000);
  } else {
    beginTaskList()
  }
}

function start() {
  // sequelize.sync({ force: true }).then(() => {
  //   console.log('所有模型已成功同步');
  // });
  backtask()
}


exports.start = start
